import base64
import jwt

import aioredis
# 配置 Redis 连接
import asyncio
import redis
from configs.auth_config import *
import json


def string_to_base64(input_string: str) -> str:
    # 将字符串转换为字节
    string_bytes = input_string.encode('utf-8')
    # 将字节编码为Base64
    base64_bytes = base64.b64encode(string_bytes)
    # 将Base64字节转换为字符串
    base64_string = base64_bytes.decode('utf-8')
    return base64_string


class JwtUti:

    def __init__(self):
        '''
        jwt处理
        '''

    def get_user_id(self, token):
        red = RedisUtil()
        return red.get(self.get_uuid(token))

    def get_uuid(self, token):
        if token is None:
            return None
        try:
            token = token.replace('Bearer', '').replace('bearer', '')
            key = string_to_base64(SECRET_KEY)
            payload = jwt.decode(token, key, algorithms=[ALGORITHM], options={"verify_signature": False})
            return payload['login_user_key']
        except Exception as e:
            return None


class RedisUtil:
    def __init__(self):
        '''
        redis处理
        '''
        self.redis_client = redis.StrictRedis(
            host=REDIS_HOST,
            port=REDIS_PORT,
            password=REDIS_PASSWORD,
            decode_responses=True
        )

    def get(self, uuid):
        if uuid is None:
            return None
        try:
            key = '%s:%s' % ("login_tokens", uuid)
            return self.redis_client.get(key)
        except:
            return None


auth_jwt = JwtUti()
